extends Node
class_name WoodStackManager

# 内部参数
var mushroom_wait_line: Array[MushroomLogic] = []
var seatable_wood_stack_list: Array[WoodStackLogic] = []

# 引用的系统
var mushroom_manager: MushroomManager

# 信号
signal mushroom_go_woodstack(mushroom: MushroomLogic, wood_stack:WoodStackLogic)

# 初始化
func _ready():
	update_woods()
	update_mushrooms()
	
	

# 获取场景上所有木桩（通过组的方式）
func update_woods():
	var woods = get_tree().get_nodes_in_group("woodstack")
	for wood in woods:
		if not wood.wood_seat_stat_changed.is_connect(_on_wood_seat_stat_changed):
			wood.wood_seat_stat_changed.connect(_on_wood_seat_stat_changed)
		if not wood.is_wood_full:
			seatable_wood_stack_list.append(wood)

# 获取场景上所有蘑菇人（通过组的方式）
func update_mushrooms():
	var mushrooms = get_tree().get_nodes_in_group("mushroom")
	for mushroom in mushrooms:
		if not mushroom.apply_for_seat.is_connect(_on_mushroom_apply):
			mushroom.apply_for_seat.connect(_on_mushroom_apply)
			mushroom.cancel_line.connect(_on_mushroom_cancel_line)
			
		

# 维护蘑菇人排队队列
# 当有新蘑菇人发起申请
func _on_mushroom_apply(mushroom):
	mushroom_seatable_check(mushroom)


# 维护场景中木桩队列
# 当木桩状态改变时（可能空出位置），轮询一次场景上的排队蘑菇人
func _on_wood_seat_stat_changed(woodstack):
	update_woods()
	for mushroom in mushroom_wait_line:
		mushroom_seatable_check(mushroom)

# 当场景木桩有移除事件发生，开始分配
# 按序获取队列中蘑菇人，并且查找其可用的木桩
func mushroom_seatable_check(mushroom):
	var mushroom_tag = mushroom.mushroom_config.mushroom_tag
	for empty_wood in seatable_wood_stack_list:
		if mushroom_tag == empty_wood.wood_config.wood_stack_mushroom_type:
			mushroom_go_woodstack.emit(mushroom, empty_wood)
			mushroom_wait_line.erase(mushroom)
			mushroom.set_mushroom_stat_ongoing()
		else:
			if not mushroom_wait_line.has(mushroom):
				mushroom_wait_line.append(mushroom)

# 当收到信号时，从排队中移除蘑菇人
func _on_mushroom_cancel_line(mushroom):
	if mushroom_wait_line.has(mushroom):
		mushroom_wait_line.erase(mushroom)
		
		
	



	
